package com.tool;

import com.alibaba.fastjson.JSONObject;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

@Service
public class CDNService {
    public CDNService() throws FileNotFoundException {
    }
    private static final Logger logger = LoggerFactory.getLogger(CDNService.class);

    private static String ACCESS_KEY;
    private static String SECRET_KEY;
    // 要上传的空间
    private static String bucketname;

//    static Properties properties=new Properties();;
//
//    static {
//        try {
//            properties.load(new FileInputStream("CDN.properties"));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
    static {
        Properties properties = new Properties();
        //使用流读取
        InputStream resourceStream = CDNService.class.getClassLoader().getResourceAsStream("CDN.properties");
        try {
            // 设置好账号的ACCESS_KEY和SECRET_KEY
            properties.load(resourceStream);
            ACCESS_KEY = properties.getProperty("ACCESS_KEY");
            SECRET_KEY = properties.getProperty("SECRET_KEY");
            bucketname = properties.getProperty("bucketname");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 密钥配置
    Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    // 构造一个带指定Zone对象的配置类,不同的七云牛存储区域调用不同的zone
    Configuration cfg = new Configuration(Region.region0());
    // ...其他参数参考类注释
    UploadManager uploadManager = new UploadManager(cfg);

    // 域名
    private static String QINIU_IMAGE_DOMAIN = "http://img.chohee.top/";


    // 简单上传，使用默认策略，只需要设置上传的空间名就可以了
    public String getUpToken() {
        return auth.uploadToken(bucketname);
    }

    public String saveImage(MultipartFile file) throws IOException {
        try {
            int dotPos = file.getOriginalFilename().lastIndexOf(".");
            if (dotPos < 0) {
                return null;
            }
            String fileExt = file.getOriginalFilename().substring(dotPos + 1).toLowerCase();
            // 判断是否是合法的文件后缀
            if (!FileTool.isFileAllowed(fileExt)) {
                return null;
            }

            String fileName = java.util.UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;
            // 调用put方法上传
            Response res = uploadManager.put(file.getBytes(), fileName, getUpToken());
            // 打印返回的信息
            if (res.isOK() && res.isJson()) {
                // 返回这张存储照片的地址
                return QINIU_IMAGE_DOMAIN + JSONObject.parseObject(res.bodyString()).get("key");
            } else {
                logger.error("七牛异常:" + res.bodyString());
                return null;
            }
        } catch (QiniuException e) {
            // 请求失败时打印的异常的信息
            logger.error("七牛异常:" + e.getMessage());
            return null;
        }
    }
}
